//
//  HMTextView.swift
//  WeiBo14
//
//  Created by HM on 16/3/11.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit

@IBDesignable
class HMTextView: UITextView {

    // 占位文字
    @IBInspectable var placeholder: String? {
        didSet{
            placeHolderLabel.text = placeholder
        }
    }
    
    override var font: UIFont? {
        didSet{
            placeHolderLabel.font = font
        }
    }
    
    override var text: String? {
        didSet{
            placeHolderLabel.hidden = hasText()
        }
    }
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI(){
        
        addSubview(placeHolderLabel)
        
        // 添加约束
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(5)
            make.top.equalTo(8)
            make.width.equalTo(SCREENW - 10)
        }
        
        // 监听文字改变,使用通知
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChanged", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    @objc private func textDidChanged() {
        placeHolderLabel.hidden = hasText()
    }
    
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    // MARK: - 懒加载控件
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.lightGrayColor()
        // 设置默认的字体大小
        label.font = UIFont.systemFontOfSize(12)
        label.text = "哈哈"
        // 多行
        label.numberOfLines = 0
        return label
    }()
    

}
